package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
)

var thriftPath string
var serviceName string
var moduleName string

func shellStr() string {
	return `#!/bin/bash

			echo "Starting generating ..."
			
			# variables
			thrift_dir="../${1}"
			service_name=${2}
			module_name=${3}
			
			# go mod
			go mod init ${module_name}
			
			# api
			mkdir api
			cd api
			cwgo server -type HTTP --idl ${thrift_dir} --service ${service_name} --module ${module_name}
			rm go.mod
			
			# rpc
			# shellcheck disable=SC2103
			cd ..
			mkdir rpc
			cd rpc
			cwgo server -type RPC --idl ${thrift_dir} --service ${service_name} --module ${module_name}
			
			echo "Generating success!"`
}

func main() {
	var file = "cwgogen.sh"
	data := []byte(shellStr())
	err := os.WriteFile(file, data, 0777)
	if err != nil {
		panic(err)
	}

	flag.StringVar(&thriftPath, "thrift", "./idl/app.thrift", "thrift file path")
	flag.StringVar(&serviceName, "service", "app", "service name")
	flag.StringVar(&moduleName, "module", "demo", "module name")

	flag.Parse()
	fmt.Println(thriftPath, serviceName, moduleName)

	shellPath := "./" + file
	command := exec.Command(shellPath, thriftPath, serviceName, moduleName)
	output, err := command.CombinedOutput()
	if err != nil {
		panic(err)
	}
	os.Remove(file)
	log.Println(string(output))
}
